import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class YunnanDgxrmzf75E9Policy(BaseTaxPolicySpider):
    name = "yunnan_dgxrmzf_75e9_policy"

    province: str = "云南省"  # 取表格
    city: str = "昭通市"  # 取表格
    county: str = "大关县"  # 取表格
    park: str = "None"  # 取表格
    source: str = "大关县人民政府"  # 取表格 同一个来源合并
    url: str = "http://www.daguan.gov.cn/channels/4730.html"  # 注明入口网址，以便后续排错

    def start_requests(self):
        self.site_code = self.url.split('.')[0].split('/')[-1]
        yield scrapy.Request(self.url, callback=self.parse_list)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath(
                "//tr//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::tr[string-length(string(.))>=5]"):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            if f'/-{self.site_code}/' in item['source_url']:
                item['source_url'] = item['source_url'].replace('/-4663/', '/4663/')
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            print(item['source_url'])
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            if '下一页' in response.text:
                total_page = response.xpath(""".""").re_first(r"""共\s*(\d+)\s*页""")
                print("total_page", total_page)
                for page_num in range(1, int(int(total_page) / 1 + 2)):
                    url = response.url.replace('.html', f'_{page_num}.html')
                    yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl yunnan_dgxrmzf_75e9_policy".split())
